﻿using System;
using System.Reflection;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using System.ComponentModel;
using Google.Apis.Calendar.v3;

namespace iCalSync
{
    public partial class launcher : Form
    {
        public CalendarService Service = null;

        public launcher()
        {
            InitializeComponent();
        }

        private void btnFichier_Click(object sender, EventArgs e)
        {
            fileDialog.ShowDialog();
            txFichier.Tag = fileDialog.FileName;
            txFichier.Text = fileDialog.SafeFileName;
            iCalSync.Properties.Settings.Default.fileIcs = fileDialog.FileName;
        }

        private void btnCal_Click(object sender, EventArgs e)
        {
            if (Service==null) Service = GCalConnect.getCalServ();
            foreach (KeyValuePair<string,string> cal in GCalClient.getAllCals(ref Service))
            {
                ListViewItem lv = new ListViewItem();
                lv.Text = cal.Key;
                lv.Tag = cal.Value;
                lbCal.Items.Add(lv);
            }
        }

        private void lbCal_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lbCal.SelectedItems != null)
            {
                txCal.Text = lbCal.SelectedItems[0].Text;
                txCal.Tag = lbCal.SelectedItems[0].Tag;
            }
        }

        private void launcher_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(iCalSync.Properties.Settings.Default.fileIcs))
            {
                System.IO.FileInfo f = new System.IO.FileInfo(iCalSync.Properties.Settings.Default.fileIcs);
                txFichier.Text = f.Name;
                txFichier.Tag = f.FullName;
            }
            txCal.Text = iCalSync.Properties.Settings.Default.calInfo;
            txCal.Tag = iCalSync.Properties.Settings.Default.calId;
        }

        private void btnParam_Click(object sender, EventArgs e)
        {
            iCalSync.Properties.Settings.Default.calId = (string)txCal.Tag;
            iCalSync.Properties.Settings.Default.calInfo = txCal.Text;
            iCalSync.Properties.Settings.Default.fileIcs = (string)txFichier.Tag;
            iCalSync.Properties.Settings.Default.Save();
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            if (BG.IsBusy)
                BG.CancelAsync();
            else
            {
                btnGo.Text = "Arrêter la synchronisation";
                if (Service == null) Service = GCalConnect.getCalServ();
                IcsFile icsFile = new IcsFile();
                GCalClient gCal = new GCalClient();
                icsFile.Parse((string)txFichier.Tag);
                gCal.UpdateEvents(icsFile, ref Service, ref BG);
                //BG.RunWorkerAsync();
            }
        }

        private void Bg_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            if (!(System.IO.File.Exists((string)txFichier.Tag)))
            {
                MessageBox.Show("Le fichier sélectionné n'est pas accessible", "Erreur", MessageBoxButtons.OK);
                e.Cancel = true;
                return;
            }
            var icsFile = new IcsFile();
            try
            {
                BG.ReportProgress(1, "Traitement du fichier source ...");
                icsFile.Parse((string)txFichier.Tag);
                BG.ReportProgress(1, "Traitement de " + icsFile.Events.Count.ToString() + " évènement(s)");
                Thread.Sleep(2000);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erreur lors du traitement du fichier source: " + ex.Message, "Erreur", MessageBoxButtons.OK);
                e.Cancel = true;
                return;
            }
            if (string.IsNullOrEmpty(iCalSync.Properties.Settings.Default.calId))
            {
                MessageBox.Show("Le calendrier n'est pas spécifié", "Erreur", MessageBoxButtons.OK);
                e.Cancel = true;
                return;
            }
            BG.ReportProgress(1, "Mise à jour du calendrier ...");
            GCalClient.CreateEvents(icsFile, ref Service, ref BG);
            if (BG.CancellationPending)
                e.Cancel = true;
            else
                e.Result = "ok";
        }

        private void Bg_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            pgB.Value = e.ProgressPercentage;
            lbl.Text = (string)e.UserState;
        }

        private void Bg_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                lbl.Text = "Mise à jour arrêtée";
            else
                lbl.Text = "Mise à jour terminée";
            btnGo.Text = "Lancer la synchronisation";
        }

    }
}
